import React, { Component } from 'react';
import { Modal, Button, Pagination, Tabs, Input, Table, message } from 'antd';

import QMFetch from 'fetch';
import filter from 'util/filter';
import './link.less';

const TabPane = Tabs.TabPane,
  Column = Table.Column;

import { QMConst } from 'qm-ux';

let host = '';

export default class Links extends Component {
  constructor(props) {
    super(props);
    this.state = {
      show: false,
      type: 'page',
      value: {
        page: null,
        goods: null,
        custom: null,
        common: null
      },
      params: {
        page: 1,
        pageSize: 10
      },
      data: {
        item: [],
        total_count: 0
      }
      //choosedKey: props.chooseData && props.chooseData.get('key')
    };
  }

  async componentDidMount() {
    host = ((await QMFetch({
      host: QMConst.HOST['v_d2c_api'],
      method: 'POST',
      url: 'domain/list',
      body: ['w']
    })) || { data: [] }).data
      .reduce((p, o) => {
        return o.domainDefault == 'Y' && (p = o.domainUrl), p;
      }, '');
    this.setState({host});
  }

  render() {
    let { show, type, value, params, data } = this.state;

    return (
      <Modal
        className="links"
        title={
          <Tabs activeKey={type} onChange={this._tabChange}>
            <TabPane tab="页面" key="page">
              <Page onSelect={this._select} />
            </TabPane>
            <TabPane tab="商品" key="goods">
              <Goods onSelect={this._select} />
            </TabPane>
            <TabPane tab="常用功能" key="common">
              <CommonLink onSelect={this._select} host={this.state.host} curUrl={this.state.value.common && this.state.value.common.url}/>
            </TabPane>
            <TabPane tab="自定义链接" key="custom">
              <div className="links-custom">
                <label>页面地址：</label>
                <Input
                  placeholder="请输入地址 如:http://example.com"
                  value={(value.custom || { url: '' }).url}
                  onChange={this._urlChange}
                />
              </div>
            </TabPane>
          </Tabs>
        }
        visible={show}
        width={800}
        onOk={this._ok}
        onCancel={this.close}
      />
    );
  }

  _tabChange = type => {
    this.setState({ type });
  };

  _urlChange = e => {
    this.state.value.custom = { url: e.target.value };
    this.setState({ value: this.state.value });
  };

  _select = value => {
    this.state.value[this.state.type] = value; //wtf?
    this.setState({ value: this.state.value });
  };

  open = (o = { type: 'page', data: null }) => {
    this.state.value[o.type] = o.data;
    this.setState({
      show: true,
      type: o.type,
      value: this.state.value
    });
  };

  close = () => {
    this.setState({ show: false });
  };

  _ok = () => {
    let { type, value } = this.state,
      { onSelect = () => {} } = this.props,
      data = value[type] || { url: '' };
    if (/^https?:\/\//gm.test(data.url)) {
      onSelect({ type, data });
      this.setState({ show: false });
    } else {
      message.warning('链接格式不正确');
    }
  };
}

export class Page extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selected: null,
      params: {
        page: 1,
        pageSize: 10
      },
      data: {
        pageInfoList: [],
        totalCount: 0
      }
    };
  }

  componentDidMount() {
    this._paging(1);
  }

  render() {
    let { params, data, selected } = this.state,
      { onSelect = () => {} } = this.props;

    return (
      <div>
        <Table dataSource={data.pageInfoList} pagination={false}>
          <Column title="名称" dataIndex="title" />
          <Column title="更新时间" render={(t, r, i) => <span>{filter.date(data.pageInfoList[i].updateTime)}</span>} />
          <Column
            title="操作"
            render={(t, r, i) =>
              data.pageInfoList[i].pageCode == (selected || {}).pageCode
                ? <span>已选取</span>
                : <a
                    onClick={() => {
                      onSelect(data.pageInfoList[i]);
                      this.setState({ selected: data.pageInfoList[i] });
                    }}
                  >
                    选取
                  </a>}
          />
        </Table>
        <Pagination
          current={params.page}
          pageSize={params.pageSize}
          defaultCurrent={params.page}
          defaultPageSize={params.pageSize}
          total={data.totalCount}
          onChange={this._paging}
          showQuickJumper
        />
      </div>
    );
  }

  _paging = async (page, pageSize = this.state.params.pageSize) => {
    let { params } = this.state;
    params.page = page;
    let res = await QMFetch({
      host: QMConst.HOST['v_x_site'],
      url: 'xsite-bin/page-svc/getPageList', // new
      body: {
        pageNo: page - 1,
        pageSize,
        platform: 'weixin',
        sc: 'H4sIAAAAAAAAA0sxSg4uyS9KBQDJOKt4CAAAAA=='
      }
    });
    (res.data || { pageInfoList: [] }).pageInfoList.forEach(o => (o.url = host + o.url));
    this.setState({ data: res.data });
  };
}

export class Goods extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selected: null,
      params: {
        page: 1,
        pageSize: 10
      },
      data: {
        aaData: [],
        iTotalDisplayRecords: 0
      }
    };
  }

  componentDidMount() {
    this._paging(1);
  }

  render() {
    let { params, data, selected } = this.state,
      { onSelect = () => {} } = this.props;

    return (
      <div>
        <Table dataSource={data.aaData} pagination={false}>
          <Column title="名称" dataIndex="name" />
          <Column
            title="操作"
            render={(t, r, i) =>
              data.aaData[i].id == (selected || {}).id
                ? <span>已选取</span>
                : <a
                    onClick={() => {
                      onSelect(data.aaData[i]);
                      this.setState({ selected: data.aaData[i] });
                    }}
                  >
                    选取
                  </a>}
          />
        </Table>
        <Pagination
          current={params.page}
          pageSize={params.pageSize}
          defaultCurrent={params.page}
          defaultPageSize={params.pageSize}
          total={data.iTotalDisplayRecords}
          onChange={this._paging}
          showQuickJumper
        />
      </div>
    );
  }

  _paging = async (page, pageSize = this.state.params.pageSize) => {
    let { params } = this.state;
    params.page = page;
    let res = await QMFetch({
      host: QMConst.HOST['v_d2c_api'],
      url: '/open_site_api/goods_list',
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
      },
      body: Object.entries({
        pageNo: page - 1,
        pageSize,
        keyword: '',
        type: 1
      })
        .reduce((p, o) => {
          return p.push(o[0] + '=' + o[1]), p;
        }, [])
        .join('&')
    });
    (res.data || { aaData: [] }).aaData.forEach(o => (o.url = host + `#/goodsDetail/${o.id}&&${o.productId}`));
    this.setState({ data: res.data });
  };
}

export class CommonLink extends Component {
  static defaultProps = {
    common_links: [
      {
        title: '领券中心',
        path: 'getcoupon',
        icon: 'coupon-redemption',
        key: 'coupon',
        type: '',
        link: '#/getcoupon'
      },
      {
        title: '首页',
        path: 'home',
        icon: 'my-home',
        key: 'home',
        type: '',
        link: '#/home'
      },
      {
        title: '购物车',
        path: 'cart',
        icon: 'shopping-cart',
        key: 'cart',
        type: '',
        link: '#/cart'
      },
      {
        title: '分类',
        path: 'category',
        icon: 'my-classification',
        key: 'category',
        type: '',
        link: '#/category'
      },
      {
        title: '个人中心',
        path: 'center',
        icon: 'personal-center',
        key: 'center',
        type: '',
        link: '#/center'
      },
      {
        title: '设置',
        path: 'userInfo',
        icon: 'set-up',
        key: 'userInfo',
        type: '',
        link: '#/userInfo'
      },
      {
        title: '我的订单',
        path: 'order-list',
        icon: 'my-order',
        key: 'order-list',
        type: 'all',
        link: '#/${path}/${type}'
      },
      {
        title: '我的积分',
        path: 'integral',
        icon: 'my-points',
        key: 'integral',
        type: 'list',
        link: '#/${path}/${type}'
      },
      {
        title: '我的优惠券',
        path: 'center-coupon',
        icon: 'my-points',
        key: 'center-coupon',
        type: '',
        link: '#/center-coupon'
      },
      {
        title: '我的余额',
        path: 'balance',
        icon: 'remaining-money',
        key: 'balance',
        type: 'list',
        link: '#/${path}/${type}'
      },
      {
        title: '我的收藏',
        path: 'user',
        icon: 'my-attention',
        key: 'collection',
        type: 'collection',
        link: '#/${path}/${type}'
      },
      {
        title: '我的评价',
        path: 'user',
        icon: 'my-evaluation',
        key: 'comments',
        type: 'comments',
        link: '#/${path}/${type}'
      },
      {
        title: '我的消息',
        path: 'user-center-mails',
        icon: 'my-news',
        key: 'userCenterMails',
        type: '',
        link: '#/user-center-mails'
      }
    ]
  };

  render() {
    let { common_links: commonLinks, onSelect = () => {}, host, curUrl = '' } = this.props;
    return (
      <div className="commonLink">
        <ul>
          {commonLinks.map((linkInfo, index) => {
            let { link = '', path = '', type = '' } = linkInfo;
            let url = host + link.replace('${path}', path).replace('${type}', type);
            let activeUser = curUrl === url ? 'active_user_true' : 'active_user_false';
            let activeClassName = curUrl === url ? 'active' : '';
            return (
              <li
                className={activeClassName}
                onClick={() => {
                  onSelect({ type: 'common', url });
                }}
              >
                <span><i className={`x-site-new-qIcon ${linkInfo.icon}`} /></span>
                <br />
                <span>{linkInfo.title}</span>
                <div className={'common_active ' + activeUser}>
                  <span
                    style={{
                      width: 11,
                      height: 8,
                      display: 'inline-block',
                      background:
                        'url(//qianmi-web.oss-cn-hangzhou.aliyuncs.com/x-site/public/images/images/icon_right.gif)'
                    }}
                  />
                </div>
              </li>
            );
          })}
        </ul>
      </div>
    );
  }
}
